<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // key和副作用函数的对应关系
        let data = {
            ok: true,
            text: 'hello world'
        }
        let activeEffect;
        function effect (fn) {
            activeEffect = fn
            fn()
        }
        // 从Set => WeakMap
        const bucket = new WeakMap()
        const obj = new Proxy(data, {
            get(target, key) {
                track(target, key)
                return target[key]
            },
            set(target, key, newVal) {
                target[key] = newVal
                trigger(target, key)
            }
        })
        effect(() => {
            console.log('effect runs');
            // 分支切换：obj.ok值为true，执行obj.text；否则都显示no，这个叫分支切换
            // 正常来看，入宫obj.ok改为false，那么之后，无论obj.text的值无论如何变，都不应该触发effect副作用函数，目前是会触发，是一种冗余的副作用函数
            document.body.innerText = obj.ok ? obj.text : 'no'
        })

        function track (target, key) {
            if (!activeEffect) return
            let depsMap = bucket.get(target)
            // 没有对应desMap
            if (!depsMap) {
                bucket.set(target, (depsMap = new Map()))
            }
            let deps = depsMap.get(key)
            // 没有对应set
            if (!deps) {
                depsMap.set(key, (deps = new Set()))
            }
            deps.add(activeEffect)
        }

        function trigger (target, key) {
            let depsMap = bucket.get(target)
            if (!depsMap) return 
            let effects = depsMap.get(key)
            // 执行副作用函数
            debugger
            effects && effects.forEach(fn => fn())
        }
    </script>
</body>
</html>